import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { getBannerApi } from '../../services/axios'


// 定义异步action函数
export const getBanner = createAsyncThunk('goods/getBanner', async () => {
  const res = await getBannerApi()
  console.log(res.data.banners)
  // return 的函数会传给action.payload
  return res.data.banners
})



// 创建store子模块
export const goodsSlice = createSlice({
  name: 'goods',
//   初始值
  initialState: {
    title:'香蕉',
    price:40,
    count:24,
    banners:[],
    loading:false
  },
  reducers: {
   changeInfo(state,action) {
    state.title = action.payload.title
    state.price = action.payload.price
    state.count = action.payload.count
    // state = action.payload
   }
  },
  extraReducers: builder => {
    builder
      .addCase(getBanner.pending, (state, action) => {
        console.log('请求中')
        state.loading = true
      })
      .addCase(getBanner.fulfilled, (state, action) => {
        state.status = 'succeeded'
        state.banners = action.payload
        state.loading = false
      })
      .addCase(getBanner.rejected, (state, action) => {
        console.log('请求失败')
        state.loading = false
      })
  }
})


export const { changeInfo } = goodsSlice.actions


export default goodsSlice.reducer